package fr.univ.surveyonline.dispatcher;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.univ.surveyonline.datastore.PMF;
import fr.univ.surveyonline.language.Language;
import fr.univ.surveyonline.model.DateHelpers;
import fr.univ.surveyonline.model.User;
import fr.univ.surveyonline.model.allEnum.Categorie;
import fr.univ.surveyonline.model.allEnum.Region;
import fr.univ.surveyonline.model.allEnum.Role;
import fr.univ.surveyonline.model.allEnum.SexeEnum;

public class RegisterServlet extends HttpServlet
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		String langue = "FR";
		for (Cookie c : req.getCookies()) {
			if (c.getName().equals("langue")) {
				langue = c.getValue(); 
				break;
			}
		}
		
		RequestDispatcher rd = null;
		String fromScreen = req.getServletPath();

		// Inscription
		if (fromScreen.equals("/deconnexion")) {
			req.getSession().removeAttribute("user");
			return;
		} 

		if (fromScreen.equals("/register")) {
			User u = (User) req.getSession().getAttribute("user");
			User aInscrire = null;
			if ((u != null)&&(u.getRole() == Role.SUPER_ADMIN)) {
				aInscrire = new User();
			}
			String message = this.getMessage(req, resp, aInscrire);
			if (message != null) {
				resp.sendError(500, "<ul>" + message + "</ul>");
			}
			if ((u != null)&&(u.getRole() == Role.SUPER_ADMIN)&&(message == null)) {
				aInscrire.setRole(Role.SONDEUR);
				PMF.makePersistent(aInscrire);
			}
			return;			
		}

		// Mettre a jour le profil
		if (fromScreen.equals("/updateProfile")) {
			User u = (User) req.getSession().getAttribute("user");
			String message = null;
			if (u == null) {
				message = (String) Language.getWord("connecter",langue);		
			} else {
				message = getMessage(req,resp,u);
				if (message != null) {
					resp.sendError(500, "<ul>" + message + "</ul>");
				}
				return;
			}			
		}
		// Valide le compte 
		if (fromScreen.equals("/validProfile")) {
			long userId = Long.valueOf(req.getParameter("id"));
			//System.out.println("<a href=\"/validProfile?id="+userId+"\">Valider l'incription</a>");;
			User u = (User) PMF.getElementById(User.class, userId);
			u.setValidity(true);
			PMF.makePersistent(u);
			rd = req.getRequestDispatcher("index.jsp");
		}

		// Se connecter a son compte 
		if (fromScreen.equals("/connexion")) {
			String login = req.getParameter("login");
			String password = req.getParameter("password");
			List<User> users = User.getAllUser();
			User u = null;
			boolean success = false;
			for (User user : users) {
				if((user.getLogin().equals(login) && (user.getPassword().equals(password))) ) {
					if (user.isValid()) {
						u = (User) PMF.getElementById(User.class, user.getKey().getId());
						success = true;						
					}
				}
			}		
			if (success) {
				req.getSession().setAttribute("user", u);
			} else {
				resp.sendError(HttpServletResponse.SC_FORBIDDEN);
			}
			return;
		}

		try {
			rd.forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		}	
	}

	private String getMessage(HttpServletRequest req, HttpServletResponse resp,User u) {
		if (u == null) {
			u = new User();
		}
		
		String langue = "FR";
		for (Cookie c : req.getCookies()) {
			if (c.getName().equals("langue")) {
				langue = c.getValue(); 
				break;
			}
		}
		
		String message = null;
			
		String login = req.getParameter("login");
		String password = req.getParameter("password");
		String password2 = req.getParameter("password2");
		String firstname = req.getParameter("firstname");
		String lastname = req.getParameter("lastname");
		String sexe = req.getParameter("sexe");
		String categorie = req.getParameter("categorie");
		String region = req.getParameter("region");
		String mail = req.getParameter("mail");
		String month = req.getParameter("month");
		String day = req.getParameter("day");
		String year = req.getParameter("year");


		// Verification que les champs sont remplis
		String[] tab = {login,password,password2,firstname,lastname,sexe,categorie,region,mail,month,day,year};
		if (!verify(tab)) {
			message = (String) Language.getWord("champs", langue);
		} else {
			Date birthday = null;
			try {
				birthday = DateHelpers.getDate(day + "/"	+ month + "/" + year);
			} catch (Exception e) {
			}
			boolean loginExist = false;
			boolean mailExist = false;
			if (!login.equals(u.getLogin())) {
				// on verifie dans la BDD
				for (User user : User.getAllUser()) {
					if (user.getLogin().equals(login)) {
						loginExist = true;
						break;
					}
				}
			}
			if (!mail.equals(u.getMail())) {
				for (User user : User.getAllUser()) {
					if (user.getMail().equals(mail)) {
						mailExist = true;
					}
				}
			}						

			if (birthday == null) {
				message = (String)Language.getWord("naissance_invalide",langue);
			} else if (birthday.compareTo(DateHelpers.getTodayDate()) >= 0) {
				message = (String)Language.getWord("naissance_superieure",langue);
			} else if (loginExist) {
				message = (String)Language.getWord("id_exist",langue);
			} else if (mailExist) {
				message = (String)Language.getWord("mail_exist",langue);
			} else if(!password.equals(password2)) {
				message = (String)Language.getWord("erreur_mdp",langue);
			} else if (!mail.matches("(?:\\w|[\\-_])+(?:\\.(?:\\w|[\\-_])+)*\\@(?:\\w|[\\-_])+(?:\\.(?:\\w|[\\-_])+)+" )) {
				message = (String)Language.getWord("erreur_mail",langue); 
			} else {
				u.setLogin(login);
				u.setPassword(password);
				u.setSexe(SexeEnum.valueOf(sexe));
				u.setMail(mail);		
				u.setBirthday(birthday);
				u.setFirstName(firstname);
				u.setLastName(lastname);
				u.setRegion(Region.valueOf(region));
				u.setCategorie(Categorie.valueOf(categorie));
				u.setRole(Role.MEMBRE);
				u.setValidity(true);
				
				PMF.makePersistent(u);	
			}
		}
		return message;
	}

	private boolean verify(String[] tab) {
		for (String s : tab) {
			if ((s == null) || s.equals("")) {
				return false;
			}
		}
		return true;
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req, resp);
	}
}
